package com.YCH.login.service.Impl;

import com.YCH.common.rabbitMQ.RabbitmqConfig;
import com.YCH.login.service.SengMSGService;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.user.dtos.registerDto;
import com.YCH.model.user.vo.MailVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Create bySeptember
 * 2019/4/7
 * 21:42
 *
 * @author 16554
 */
@Service
@Log4j2
public class SengMSGServiceImpl implements SengMSGService {
    // redis数据存储过期时间
    private static final int sms_term_of_validity = 30;
    // rabbitmq routtingkey
    private static final String ROUTINGKEY = "inform.email";
    // rabbitmq 消息过期时间,单位：毫秒,这里3分钟
    private static final String EXPIRATION = "300000";
    @Autowired
    private RedisTemplate redisTemplate;
    // 构建消息
    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 发送注册代码邮件
    @Override
    public ResponseResult sendActiveCode(HttpServletRequest request, registerDto dto){
        // 参数校验
        String uuid = null;
        if(dto.getUuid().isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }else {
            if(!"4".equals(String.valueOf(dto.getUuid().charAt(12)))){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            uuid = dto.getUuid();
        }
        //发送邮件
        MailVo mailVo = new MailVo();
        mailVo.setFrom("yuchuanhui999@qq.com");
        mailVo.setTo(dto.getEmail());
        mailVo.setSubject("感谢您使用云N记" + dto.getEmail());
        mailVo.setIsHtml(true);
        String code = getCode();
        Date date = new Date();
        //Fri Nov 29 10:05:00 CST 2019
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datef = sdf.format(date);
        String text = "<div style=\"background-color: #ECECEC; padding-bottom: 160px;\">\n" +
                "<div style=\"width: 800px;margin: 0px auto;padding: 50px;\">\n" +
                "    <div style=\"height: 80px;background-color: #49bcff;border-top-left-radius: 5px;border-top-right-radius: 5px;padding-left: 30px;font-family: Arial, Helvetica, sans-serif;\">\n" +
                "        <h2 style=\"padding-top: 25px;color: white;font-family: Arial, Helvetica, sans-serif;\">欢迎加入云N记!</h2>\n" +
                "    </div>\n" +
                "    <div style=\"background-color: #fff;padding-left: 30px;padding-bottom: 30px;border-bottom: 1px solid #ccc;border-top-left-radius: 5px;border-top-right-radius: 5px;font-family: Arial, Helvetica, sans-serif;\">\n" +
                "        <h2 style=\"padding-top: 20px;padding-bottom: 20px;font-family: Arial, Helvetica, sans-serif;\">亲爱的用户您好</h2>\n" +
                "        <p style=\"padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">您的邮箱：<b><span>" + dto.getEmail() + "</span></b><span style=\"color:red;margin-left:20px\">"+sms_term_of_validity+"分钟<span>内有效</p>\n" +
                "        <p style=\"padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">您的激活码：<b><span>" + code + "</span></b></p>\n" +
                "        <p style=\"padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">您注册时的日期：<b><span>" + datef + "</span></b></p>\n" +
                "        <p style=\"padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">当您在使用本网站时，务必要遵守法律法规</p>\n" +
                "        <p style=\"padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">如果您有什么疑问可以联系管理员，Email: <b>u97966979@163.com</b></p>\n" +
                "    </div>\n" +
                "    <div style=\"background-color: #fff;border-bottom-left-radius: 5px;border-bottom-right-radius: 5px;padding: 35px;font-family: Arial, Helvetica, sans-serif;\">\n" +
                "        <p style=\"color: #747474;padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">此为系统邮件，请勿回复</p>\n" +
                "        <p style=\"color: #747474;padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">请保管好您的信息，避免被他人盗用</p>\n" +
                "        <p style=\"color: #747474;padding-top: 10px;font-family: Arial, Helvetica, sans-serif;\">©YCH</p>\n" +
                "    </div>\n" +
                "</div>\n" +
                "</div>";
        mailVo.setText(text);
        MessageProperties messageProperties = new MessageProperties();
        // 设置过期时间，
        messageProperties.setExpiration(EXPIRATION);
        // 设置消息唯一表示
        // 发布消息的时候使用，存储在消息的headers中
        CorrelationData correlationData = new CorrelationData(dto.getUuid());
        Message message = new Message(JSONObject.toJSONBytes(mailVo),messageProperties);
        try {
            // 异步发送邮件
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPIC_INFORM, ROUTINGKEY,message, correlationData);
            // 保存到redis
            // hash 散列 md5addr {code:code,count:count} 1天后过期
            BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(uuid);
            boundValueOperations.set(code);
            // 设置30分钟过期
            boundValueOperations.expire(sms_term_of_validity, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),uuid);
    }

    /**
     * 产生4位随机字符串
     */
    private String getCode() {
        String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        int size = base.length();
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 6; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }
}